package com.japher.hackson.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.text.format.DateFormat;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import com.common.image_loader.LocalImageManager;

public final class CameraUtil
{

	private static final String TAG = "MicroMsg.SDK.CameraUtil";
	public static final String IMAGE_UNSPECIFIED = "image/*";
	private static String filePath = null;

	public static final int PHOTOHRAPH = 11;// 拍照
	public static final int PHOTOPICKALBUM = 12; // 取相册
	public static final int PHOTORESOULT = 13;// 缩放结果

	private CameraUtil()
	{
		// can't be instantiated
	}

	public static void zoomPhoto(Uri uri, final Activity context, int outputX, int outputY, int aspectX, int aspectY, int cmd)
	{
		if (uri == null)
			return;

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", aspectX);
		intent.putExtra("aspectY", aspectY);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("noFaceDetection", true); // no face detection
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		intent.putExtra("scale", true);
		intent.putExtra("outputX", Tools.getPixelByDip(context, outputX));
		intent.putExtra("outputY", Tools.getPixelByDip(context, outputY));
		intent.putExtra("return-data", false);
		intent.putExtra("scaleUpIfNeeded", true);// 去黑边

		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(zoomPath)));
		context.startActivityForResult(intent, cmd);
	}

	public static void resolveImageView(Bitmap photo, ImageView imageView,int type,boolean isRound)
	{
		if (photo == null)
			return;

		File file = new File(LocalImageManager.dbPath + Tools.getMD5("movie163" + type + 163));
		FileOutputStream out = null;
		try
		{
			if(file.exists())
			{
				file.delete();
			}
			out = new FileOutputStream(file);
			photo.compress(Bitmap.CompressFormat.JPEG, 75, out);

			if(isRound)
			{
				imageView.setImageBitmap(makeCircleBitmap(photo.getWidth()/2,photo));
			}
			else
			{
				imageView.setImageBitmap(photo);
			}
			
			imageView.invalidate();
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (Exception e) {
			// TODO: handle exception
		}
	}

	public static boolean takePhotoFromAlbum(final Activity activity, final int cmd)
	{

		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
		{
			try
			{
				Intent intent = new Intent(Intent.ACTION_PICK, null);
				intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
				activity.startActivityForResult(intent, cmd);
			}
			catch (ActivityNotFoundException e)
			{
				Toast.makeText(activity, "找不到系统相机！", Toast.LENGTH_LONG).show();

			}
		}
		else
		{
			Toast.makeText(activity, "没有存储卡取不到相册哦！", Toast.LENGTH_LONG).show();
		}

		return true;

	}

	public static final String zoomPath = LocalImageManager.dbPath+"zoom.jpg";
	public static final String camerPath = LocalImageManager.dbPath+"temp.jpg";
	public static boolean takePhoteFromCamera(final Activity activity, final int cmd)
	{
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
		{

			try
			{
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(camerPath)));
				activity.startActivityForResult(intent, cmd);
			}
			catch (ActivityNotFoundException e)
			{
				Toast.makeText(activity, "找不到系统相册！", Toast.LENGTH_LONG).show();

			}
		}
		else
		{
			Toast.makeText(activity, "没有存储卡不可以拍照哦！", Toast.LENGTH_LONG).show();
		}

		return true;
	}

	public static boolean takePhoto(final Activity activity, final String dir, final String filename, final int cmd)
	{
		filePath = dir + filename;

		final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		final File cameraDir = new File(dir);
		if (!cameraDir.exists())
		{
			return false;
		}

		final File file = new File(filePath);
		final Uri outputFileUri = Uri.fromFile(file);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
		try
		{
			activity.startActivityForResult(intent, cmd);

		}
		catch (final ActivityNotFoundException e)
		{
			return false;
		}
		return true;
	}

	public static String getResultPhotoPath(Context context, final Intent intent, final String dir)
	{
		if (filePath != null && new File(filePath).exists())
		{
			return filePath;
		}

		return resolvePhotoFromIntent(context, intent, dir);
	}

	public static String resolvePhotoFromIntent(final Context ctx, final Intent data, final String dir)
	{
		if (ctx == null || data == null || dir == null)
		{
			Log.e(TAG, "resolvePhotoFromIntent fail, invalid argument");
			return null;
		}

		String filePath = null;

		final Uri uri = Uri.parse(data.toURI());
		Cursor cu = ctx.getContentResolver().query(uri, null, null, null, null);
		if (cu != null && cu.getCount() > 0)
		{
			try
			{
				cu.moveToFirst();
				final int pathIndex = cu.getColumnIndex(MediaColumns.DATA);
				Log.e(TAG, "orition: " + cu.getString(cu.getColumnIndex(MediaStore.Images.ImageColumns.ORIENTATION)));
				filePath = cu.getString(pathIndex);
				Log.d(TAG, "photo from resolver, path:" + filePath);

			}
			catch (Exception e)
			{
				e.printStackTrace();
			}

		}
		else if (data.getData() != null)
		{
			filePath = data.getData().getPath();
			if (!(new File(filePath)).exists())
			{
				filePath = null;
			}
			Log.d(TAG, "photo file from data, path:" + filePath);

		}
		else if (data.getAction() != null && data.getAction().equals("inline-data"))
		{

			try
			{
				final String fileName = Tools.getMD5(DateFormat.format("yyyy-MM-dd-HH-mm-ss", System.currentTimeMillis()).toString().getBytes().toString()) + ".png";
				filePath = dir + fileName;

				final Bitmap bitmap = (Bitmap) data.getExtras().get("data");
				final File file = new File(filePath);
				if (!file.exists())
				{
					file.createNewFile();
				}

				BufferedOutputStream out;
				out = new BufferedOutputStream(new FileOutputStream(file));
				final int cQuality = 100;
				bitmap.compress(Bitmap.CompressFormat.PNG, cQuality, out);
				out.close();
				Log.d(TAG, "photo image from data, path:" + filePath);

			}
			catch (final Exception e)
			{
				e.printStackTrace();
			}

		}
		else
		{
			if (cu != null)
			{
				cu.close();
				cu = null;
			}
			Log.e(TAG, "resolve photo from intent failed");
			return null;
		}
		if (cu != null)
		{
			cu.close();
			cu = null;
		}
		return filePath;
	}

	public static Bitmap toRoundBitmap(Bitmap bitmap)
	{
		Bitmap output = null;

		if (bitmap != null)
		{
			if (bitmap.isMutable())
			{
				output = bitmap;
			}
			else
			{
				try
				{
					output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_4444);
				}
				catch (OutOfMemoryError error)
				{

				}
			}

			if (output != null)
			{
				Canvas canvas = new Canvas(output);
				final int color = 0xffffffff;
				final Paint paint = new Paint();
				final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
				final RectF rectF = new RectF(rect);
				final float roundPx = bitmap.getWidth() / 2;
				paint.setAntiAlias(true);
				canvas.drawARGB(0, 0, 0, 0);
				paint.setColor(color);

				canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
				paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
				canvas.drawBitmap(bitmap, rect, rect, paint);
			}

			if (!bitmap.isMutable())
			{
				bitmap.recycle();
			}
		}

		return output;
	}

	public static Bitmap makeCircleBitmap(int radius, Bitmap src)
	{

		if (src == null || radius <= 0)
			return null;

		Bitmap bmScaled = null;
		Canvas canvas = new Canvas();
		Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
		Path mPath = new Path();
		paint.setAntiAlias(true);
		Bitmap bm = Bitmap.createBitmap(2 * radius, 2 * radius, Config.ARGB_8888);
		canvas.setBitmap(bm);
		paint.setFilterBitmap(true);
		paint.setAntiAlias(true);

		Bitmap destBmp = getScaledCenterBitmap(radius, src);

		if (src.getWidth() > src.getHeight())
		{
			bmScaled = Bitmap.createScaledBitmap(src, 2 * radius * src.getWidth() / src.getHeight(), 2 * radius, true);
			canvas.drawBitmap(bmScaled, -(bmScaled.getWidth() - bmScaled.getHeight()) / 2, 0, paint);
		}
		else
		{
			bmScaled = Bitmap.createScaledBitmap(src, 2 * radius, 2 * radius * src.getHeight() / src.getWidth(), true);
			canvas.drawBitmap(bmScaled, 0, -(bmScaled.getHeight() - bmScaled.getWidth()) / 2, paint);
		}

		canvas.drawBitmap(destBmp, 0, 0, paint);
		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
		canvas.drawBitmap(makeDst(radius), 0, 0, paint);

		paint.setXfermode(null);

		return bm;
	}

	private static Bitmap getScaledCenterBitmap(int radius, Bitmap src)
	{
		if (src == null || radius <= 0)
			return null;

		Bitmap bmScaled = null;
		Canvas canvas = new Canvas();
		Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
		Path mPath = new Path();
		paint.setAntiAlias(true);
		Bitmap bm = Bitmap.createBitmap(2 * radius, 2 * radius, Config.ARGB_8888);
		canvas.setBitmap(bm);
		if (src.getWidth() > src.getHeight())
		{
			bmScaled = Bitmap.createScaledBitmap(src, 2 * radius * src.getWidth() / src.getHeight(), 2 * radius, true);

			canvas.drawBitmap(bmScaled, -(bmScaled.getWidth() - bmScaled.getHeight()) / 2, 0, paint);

		}
		else
		{
			bmScaled = Bitmap.createScaledBitmap(src, 2 * radius, 2 * radius * src.getHeight() / src.getWidth(), true);

			canvas.drawBitmap(bmScaled, 0, -(bmScaled.getHeight() - bmScaled.getWidth()) / 2, paint);
		}
		return bm;
	}

	private static Bitmap makeDst(int r)
	{
		Bitmap bm = Bitmap.createBitmap(2 * r, 2 * r, Bitmap.Config.ARGB_8888);
		Canvas c = new Canvas(bm);
		Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);

		p.setColor(Color.argb(255, 255, 255, 255));
		c.drawCircle(r, r, r, p);
		return bm;
	}
}
